/**
 * Copyright 2011 Mark Wyszomierski
 */
package com.unicampmaps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * https://developer.foursquare.com/docs/oauth.html
 * https://foursquare.com/oauth/
 * 
 * @date May 17, 2011
 * @author Mark Wyszomierski (markww@gmail.com)
 */
public class ActivityWebView extends Activity {

	/**
	 * Get these values after registering your oauth app at:
	 * https://foursquare.com/oauth/
	 */
	public static final String CALLBACK_URL = "http://www.students.ic.unicamp.br/~ra104864/";
	public static final String CLIENT_ID = "3FD4BRBC3GB1XTIX0MCUOOSJVJ4NXTE5QBOK15AZMKI2IKGE";

	public static final String USER_INFO = "https://api.foursquare.com/v2/users/self?oauth_token=";
	public static final String API_VERSION = "&v=20130620";

	private String name;
	private String email;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);

		String url = "https://foursquare.com/oauth2/authenticate"
				+ "?client_id=" + CLIENT_ID + "&response_type=token"
				+ "&redirect_uri=" + CALLBACK_URL;

		WebView webview = (WebView) findViewById(R.id.webview);
		webview.getSettings().setJavaScriptEnabled(true);
		webview.setWebViewClient(new WebViewClient() {
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				String fragment = "#access_token=";
				int start = url.indexOf(fragment);
				if (start > -1) {
					// You can use the accessToken for api calls now.
					String accessToken = url.substring(
							start + fragment.length(), url.length());

					getUserName(USER_INFO + accessToken + API_VERSION);

					SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(getApplicationContext());
					Editor edit = prefs.edit();
					edit.putString("token", accessToken);
					edit.putString("name", name);
					edit.putString("email", email);
					edit.commit();

					finish();
				}
			}
		});
		webview.loadUrl(url);
	}

	private DefaultHttpClient createHttpClient() {
		final SchemeRegistry supportedSchemes = new SchemeRegistry();

		supportedSchemes.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		supportedSchemes.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));

		final HttpParams params = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSoTimeout(params,
				FoursquareVenueFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);

		HttpClientParams.setRedirecting(params, false);

		final ClientConnectionManager com = new ThreadSafeClientConnManager(
				params, supportedSchemes);

		return new DefaultHttpClient(com, params);
	}

	private String getUrlJSON(String url) {
		HttpGet httpGet = new HttpGet(url);

		DefaultHttpClient httpClient = createHttpClient();

		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			String response = EntityUtils.toString(httpResponse.getEntity());

			return response;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	private void getUserName(String url) {
		String json = getUrlJSON(url);

		try {
			JSONObject user = (JSONObject) ((JSONObject) new JSONObject(json)
					.get("response")).get("user");
			name = user.getString("firstName") + " "
					+ user.getString("lastName");
			JSONObject contact = (JSONObject) user.get("contact");
			email = contact.getString("email");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}